package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.*;

import cn.hutool.core.bean.BeanException;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateTimeZoneConverter;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.ProductVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 设备Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-08-01
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService
{
    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private IoTDAClient iotDAClient;

    @Autowired
    private RedisTemplate redisTemplate;

    public static final String IOT_ALL_PRODUCT_LIST= "iot:all_product_list";

    /**
     * 查询设备
     * 
     * @param id 设备主键
     * @return 设备
     */
    @Override
    public Device selectDeviceById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询设备列表
     * 
     * @param device 设备
     * @return 设备
     */
    @Override
    public List<Device> selectDeviceList(Device device)
    {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备
     * 
     * @param device 设备
     * @return 结果
     */
    @Override
    public int insertDevice(Device device)
    {
        return save(device) ? 1 : 0;
    }

    /**
     * 修改设备
     * 
     * @param device 设备
     * @return 结果
     */
    @Override
    public int updateDevice(Device device)
    {
        return updateById(device) ? 1 : 0;
    }

    /**
     * 批量删除设备
     * 
     * @param ids 需要删除的设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除设备信息
     * 
     * @param id 设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 同步产品列表
     */
    @Override
    public void syncProductList() {
        // 请求参数
        ListProductsRequest listProductsRequest = new ListProductsRequest();
        // 设置条数
        listProductsRequest.setLimit(50);
        ListProductsResponse response = iotDAClient.listProducts(listProductsRequest);
        if (response.getHttpStatusCode() != 200){
            throw new BeanException("同步产品列表失败");
        }
        redisTemplate.opsForValue().set(IOT_ALL_PRODUCT_LIST, JSONUtil.toJsonStr(response.getProducts()));
    }

    /**
     * 获取所有产品列表
     * @return
     */
    @Override
    public List<ProductVo> allProduct() {
        String jsonStr = (String) redisTemplate.opsForValue().get(IOT_ALL_PRODUCT_LIST);
        if (jsonStr == null){
            return Collections.emptyList();
        }
        return JSONUtil.toList(jsonStr, ProductVo.class);
    }

        /**
     * 注册设备
     * <p>
     * 该方法用于注册一个新的设备。在注册前会进行多项校验，包括设备名称、设备标识以及同一位置是否已绑定相同产品。
     * 若校验通过，则调用物联网平台接口完成设备注册，并将设备信息保存到本地数据库。
     *
     * @param deviceDto 包含待注册设备信息的数据传输对象，不能为空
     */
    @Override
    public void register(DeviceDto deviceDto) {
        // 判断设备名称是否存在
        long count = this.count(Wrappers.<Device>lambdaQuery().eq(Device::getDeviceName, deviceDto.getDeviceName()));
        if (count > 0){
            throw new BeanException("设备已存在");
        }

        // 判断设备标识是否存在
        count=this.count(Wrappers.<Device>lambdaQuery().eq(Device::getNodeId, deviceDto.getNodeId()));
        if (count > 0){
            throw new BeanException("设备标识已存在");
        }

        // 判断同一位置是否绑定了相同的产品
        count=this.count(Wrappers.<Device>lambdaQuery()
                .eq(Device::getProductKey, deviceDto.getProductKey())
                .eq(Device::getBindingLocation, deviceDto.getBindingLocation())
                .eq(Device::getLocationType, deviceDto.getLocationType())
                .eq(deviceDto.getPhysicalLocationType()!=null,Device::getPhysicalLocationType, deviceDto.getPhysicalLocationType())
        );
        if (count > 0){
            throw new BeanException("同一位置已绑定相同产品");
        }

        // 调用物联网平台接口注册设备
        AddDeviceRequest request = new AddDeviceRequest();
        AddDevice body=new AddDevice();
        body.withProductId(deviceDto.getProductKey());
        body.withDeviceName(deviceDto.getDeviceName());
        body.withNodeId(deviceDto.getNodeId());

        // 设置设备认证密钥
        AuthInfo authInfo=new AuthInfo();
        String secret = UUID.randomUUID().toString().replaceAll("-", "");
        authInfo.withSecret(secret);
        body.withAuthInfo(authInfo);
        request.setBody(body);

        AddDeviceResponse response;
        try {
            response = iotDAClient.addDevice(request);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException("物联网接口 - 注册设备，调用失败");
        }

        // 本地保存设备信息
        // 属性拷贝
        Device device = BeanUtil.toBean(deviceDto, Device.class);
        // 设置密钥
        device.setSecret(secret);
        // 设置设备ID和绑定状态
        device.setIotId(response.getDeviceId());
        this.save(device);
    }

    /**
     * 获取设备详情
     * <p>
     * 该方法用于获取指定设备详情，包括设备基本信息、设备状态、设备密钥等信息。
     *
     * @param iotId 设备ID，不能为空
     * @return 设备详情数据传输对象
     */
    @Override
    public DeviceDetailVo getInfo(String iotId) {
        //查询本地设备数据
        Device device = this.getOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotId));
        if (ObjectUtil.isEmpty( device)) {
            throw new BeanException("设备不存在");
        }
        //调用物联网接口查询设备详情
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.setDeviceId(iotId);
        ShowDeviceResponse response=iotDAClient.showDevice(request);
        if (response.getHttpStatusCode()!=200) {
            throw new BeanException("物联网接口 - 查询设备详情，调用失败");
        }
        String status = response.getStatus();
        String activeTimeStr = response.getActiveTime();
        //封装返回数据
        DeviceDetailVo detailVo =BeanUtil.toBean(device, DeviceDetailVo.class);
        detailVo.setBindingLocation(Long.valueOf(device.getBindingLocation()));
        detailVo.setDeviceStatus(status);
        //转化时间类型
        if (StringUtils.isNotEmpty(activeTimeStr)) {
            LocalDateTime activeTime = LocalDateTimeUtil.parse(activeTimeStr, DatePattern.UTC_MS_PATTERN);
            activeTime= DateTimeZoneConverter.utcToShanghai(activeTime);
            detailVo.setActiveTime(activeTime);
        }
        return detailVo;
    }

    /**
     * 查询设备服务属性
     * <p>
     * 该方法用于查询指定设备服务属性，包括属性名称、属性值、属性描述等信息。
     *
     * @param iotId 设备ID，不能为空
     * @return 设备服务属性列表
     */
    @Override
    public List<Map<String, Object>> queryServiceProperties(String iotId) {
        //查询IOT上的数据
        ShowDeviceShadowRequest request=new ShowDeviceShadowRequest();
        request.setDeviceId(iotId);
        ShowDeviceShadowResponse response = iotDAClient.showDeviceShadow(request);
        if (response.getHttpStatusCode()!=200) {
            throw new BeanException("查询设备影子数据失败");
        }
        //获取上报数据聚合
        List<DeviceShadowData> shadowList =response.getShadow();
        if (CollectionUtil.isEmpty(shadowList)) {
            return Collections.emptyList();
        }

        DeviceShadowProperties reported = shadowList.get(0).getReported();
        Object properties = reported.getProperties();
        JSONObject entries = JSONUtil.parseObj(properties);

        //获取设备上报时间
        String eventTime = reported.getEventTime();
        LocalDateTime parse = LocalDateTimeUtil.parse(eventTime, "yyyyMMdd'T'HHmmss'Z'");
        LocalDateTime localDateTime = DateTimeZoneConverter.utcToShanghai(parse);
        //封装数据
        List<Map<String, Object>> list = new ArrayList<>();
        entries.forEach((key, value) -> {
            Map<String, Object> map = new HashMap<>();
            map.put("functionId", key);
            map.put("value", value);
            map.put("eventTime", localDateTime);
            list.add(map);
        });
        return list;
    }

    /**
     * 修改设备信息
     * <p>
     * 该方法用于修改指定设备的信息，包括设备名称、设备描述、设备位置等信息。
     *
     * @param deviceDto 设备数据传输对象，不能为空
     */
    @Override
    public void edit(DeviceDto deviceDto) {
        // 查询本地数据库获取设备的物联网平台ID
        Device device = this.getById(deviceDto.getId());
        if (device == null || StringUtils.isEmpty(device.getIotId())) {
            throw new BeanException("设备不存在或未正确注册到物联网平台");
        }
        //查询IOT上的设备信息
        ShowDeviceRequest request=new ShowDeviceRequest();
        request.setDeviceId(device.getIotId());
        ShowDeviceResponse response = iotDAClient.showDevice(request);
        if (response.getHttpStatusCode()!=200) {
            throw new BeanException("物联网接口 - 查询设备详情，调用失败");
        }
        //修改IOT上的设备信息
        UpdateDeviceRequest updateDeviceRequest=new UpdateDeviceRequest();
        updateDeviceRequest.setDeviceId(device.getIotId());
        UpdateDevice body=new UpdateDevice();
        body.withDeviceName(deviceDto.getDeviceName());
        body.withDescription(deviceDto.getDeviceDescription());
        updateDeviceRequest.setBody(body);
        UpdateDeviceResponse updateDeviceResponse = iotDAClient.updateDevice(updateDeviceRequest);
        if (updateDeviceResponse.getHttpStatusCode()!=200) {
            throw new BeanException("物联网接口 - 修改设备信息，调用失败");
        }
        //修改本地设备信息
        Device updateDevice = BeanUtil.toBean(deviceDto, Device.class);
        this.updateById(updateDevice);
        redisTemplate.delete(IOT_ALL_PRODUCT_LIST);
    }

        /**
     * 删除设备
     * <p>
     * 该方法用于删除指定设备，包括设备信息、设备影子数据等信息。
     *
     * @param iotId 设备ID，不能为空
     */
    @Override
    public void removeByIotId(String iotId) {
        // 查询本地数据库获取设备的物联网平台ID
        Device device = this.getOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotId));
        if (device == null || StringUtils.isEmpty(device.getIotId())) {
            throw new BeanException("设备不存在或未正确注册到物联网平台");
        }

        // 查询IOT上的设备信息
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.setDeviceId(iotId);
        ShowDeviceResponse response = iotDAClient.showDevice(request);
        if (response.getHttpStatusCode() != 200) {
            throw new BeanException("物联网接口 - 删除设备信息，调用失败");
        }

        // 删除IOT上的设备信息
        DeleteDeviceRequest deleteDeviceRequest = new DeleteDeviceRequest();
        deleteDeviceRequest.setDeviceId(iotId);
        DeleteDeviceResponse deleteDeviceResponse = iotDAClient.deleteDevice(deleteDeviceRequest);
        if (deleteDeviceResponse.getHttpStatusCode() != 204) {
            throw new BeanException("物联网接口 - 删除设备信息，调用失败");
        }

        // 删除本地数据库中的设备记录并清除相关缓存
        this.removeById(device.getId());
        redisTemplate.delete(IOT_ALL_PRODUCT_LIST);
    }

    @Override
    public AjaxResult queryProduct(String productKey) {
        // 参数校验
        if(StringUtils.isEmpty(productKey)) {
            throw new BaseException("请输入正确的参数");
        }
        // 调用华为云IOT平台接口
        ShowProductRequest showProductRequest = new ShowProductRequest();
        showProductRequest.setProductId(productKey);
        ShowProductResponse response;

        try {
            response = iotDAClient.showProduct(showProductRequest);
        } catch (Exception e) {
            throw new BaseException("查询产品详情失败");
        }
        // 判断是否存在服务数据
        List<ServiceCapability> serviceCapabilities = response.getServiceCapabilities();
        if(CollUtil.isEmpty(serviceCapabilities)) {
            return AjaxResult.success(Collections.emptyList());
        }

        return AjaxResult.success(serviceCapabilities);
    }
}
